package redis

import (
	"context"
	"fmt"
	"log"

	"github.com/go-redis/redis/v8"
)

var (
	Client *redis.Client
	ctx    = context.Background()
)

// InitRedisClients 初始化Redis客户端
func InitRedisClients(host string, port string) error {
	log.Printf("Initializing  : %s:%s",
		host, port)

	// 初始化股票Redis客户端
	Client = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", host, port),
		Password: "", // 无密码
		DB:       0,  // 默认DB
	})

	// 测试股票Redis连接
	if _, err := Client.Ping(ctx).Result(); err != nil {
		log.Printf("Failed to connect to  Redis: %v", err)
		return fmt.Errorf("failed to connect to  Redis: %w", err)
	}
	log.Printf("Successfully connected to  Redis at %s:%s", host, port)

	return nil
}

// GetStockClient 获取股票Redis客户端
func GetClient() *redis.Client {
	if Client == nil {
		log.Fatal("Stock Redis client is nil, make sure InitRedisClients was called")
	}
	return Client
}

// CloseConnections 关闭所有Redis连接
func CloseConnections() {
	if Client != nil {
		if err := Client.Close(); err != nil {
			log.Printf("Error closing stock Redis connection: %v", err)
		} else {
			log.Println("Stock Redis connection closed successfully")
		}
	}

}
